package live.zs;

import io.quarkus.hibernate.reactive.panache.Panache;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import io.smallrye.mutiny.Uni;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import live.zs.entity.TbOrderEntity;
import live.zs.repo.OrderRepository;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;

@Path("/hello")
public class GreetingResource {

    @ConfigProperty(name = "greeting.message")
    String message;

    @ConfigProperty(name = "greeting.suffix", defaultValue = "!")
    String suffix;

    @ConfigProperty(name = "greeting.name")
    Optional<String> name;

    @Inject
    OrderRepository orderRepository;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello RESTEasy " + message + " " + name.orElse("world") + suffix;
    }

    @GET
    @Path("orders")
    public Uni<List<PanacheEntityBase>> order() {
        return TbOrderEntity.listAll();
    }


    @GET
    @Path("add")
    public Uni<Response> reactiveAdd() {
        Random random = new Random();
        TbOrderEntity orderEntity = new TbOrderEntity();
        orderEntity.setOrderId(random.nextLong());
        orderEntity.setOrderDesc("ss");
        orderEntity.setUserId(2L);
        return Panache.<TbOrderEntity>withTransaction(orderEntity::persist).onItem().transform(inserted -> Response.created(URI.create("order")).build());
    }

    @GET
    @Path("add")
    public Uni<PanacheEntityBase> add() {
        Random random = new Random();
        TbOrderEntity orderEntity = new TbOrderEntity();
        orderEntity.setOrderId(random.nextLong());
        orderEntity.setOrderDesc(UUID.randomUUID().toString());
        orderEntity.setUserId(random.nextLong());
        return orderEntity.persist();
    }

    @GET
    @Path("del/{id}")
    public Uni<Boolean> del(Long id) {
        return orderRepository.deleteById(id);
    }
}
